package org.teremail.panto;

import static java.lang.String.format;
import static org.teremail.panto.TestConstants.BODY_FORMAT;
import static org.teremail.panto.TestConstants.EPI_FORMAT;
import static org.teremail.panto.TestConstants.PRE_FORMAT;
import static org.teremail.panto.TestConstants.MULTI_FORMAT;

import java.io.IOException;
import java.io.InputStream;

public class PantoContentHandler implements ContentHandler {

    StringBuilder sb = new StringBuilder();
    
    public void body(BodyHeader header, InputStream in) throws IOException {
        String t = header.getContentType().getType() + "/" + header.getContentType().getSubType();
        //IOUtil.dump("panto.text", in);
        sb.append(format(BODY_FORMAT, t, count(in)));
    }
    
    public long count(InputStream in) throws IOException {
        long i = IOUtil.count(in);
//        if (i > 1) {
//            i -= 2;
//        }
        return i;
    }

    public void endBodyPart() {
        sb.append("};");
    }

    public void endHeader() {
        sb.append("];");
    }

    public void endMessage() {
        sb.append("};");
    }

    public void endMultipart() {
        sb.append("};");
    }

    public void epilogue(InputStream in) throws IOException {
        sb.append(format(EPI_FORMAT, IOUtil.count(in)));
    }

    public void field(String fieldData) {
        sb.append(fieldData);
        sb.append(";");
    }

    public void preamble(InputStream in) throws IOException {
        //String s = IOUtil.toString(in, "US-ASCII");
        //System.out.println("{" + s + "}");
        sb.append(format(PRE_FORMAT, count(in)));
        //sb.append("preamble: " + s);
    }

    public void startBodyPart() {
        sb.append("bodyPart:{");
    }

    public void startHeader() {
        sb.append("header:[");
    }

    public void startMessage() {
        sb.append("message:{");
    }

    public void startMultipart(BodyHeader header) {
        System.out.println("** Boundary = " + header.getContentType().getBoundary());
        String t = header.getContentType().getType() + "/" + header.getContentType().getSubType();
        String b = header.getContentType().getBoundary();
        sb.append(format(MULTI_FORMAT, t, b));
    }
    
    public String toString() {
        return sb.toString();
    }

}
